﻿#include "FileSender.h"
#include <QTimer>
#include <QDebug>
#include <QDataStream>
#include <qbytearray.h>
FileSender::FileSender(const QHostAddress &groupAddress, quint16 port, QObject *parent)
    : QObject(parent), m_groupAddress(groupAddress), m_port(port),
      m_packetSequenceNumber(0), m_timer(new QTimer(this)) {

    if (!m_socket.isOpen()) {
        // 套接字未绑定，尝试绑定到指定端口
        if (!m_socket.bind(QHostAddress::Any, m_port, QUdpSocket::ShareAddress)) {
            // 绑定失败，处理错误
            qDebug() << "绑定端口失败：" << m_socket.errorString();
        } else {
            // 绑定成功
            qDebug() << "绑定端口成功";
        }
    } else {
        // 套接字已经打开（绑定）
        qDebug() << "套接字已经绑定到端口" << m_port;
    }

    QByteArray startSignal = "START";
    m_socket.writeDatagram(startSignal, m_groupAddress, m_port);


}

FileSender::~FileSender() {
    m_file->close();
    delete[] spx_video;

    qDebug("FileSender destroyed");
}

void FileSender::startSending(QString &filePath) {
    m_file=new QFile(filePath);
    if (!m_file->open(QIODevice::ReadOnly)) {
        qFatal("Cannot open file for reading: %s", qPrintable(filePath));
    }
    connect(m_timer, &QTimer::timeout, this, &FileSender::sendNextPacket);
    m_timer->start(5);
}

void FileSender::sendNextPacket() {
    if(m_file==NULL)
    {
        return;
    }
    if (m_file->atEnd()) {
        QByteArray endSignal = "END";
        m_socket.writeDatagram(endSignal, m_groupAddress, m_port);
        qDebug("Sending END signal");
        m_timer->stop();
        return;
    }

    QByteArray datagram(30767,'0');
    int bytesRead = m_file->read(datagram.data(), datagram.size());
    if (bytesRead < 0) {
        qWarning("Error reading from file");
        return;
    }

    if ((datagram[0] == static_cast<char>(0xA5)) && (datagram[1] == static_cast<char>(0xA5)))
    {
        // 去掉前63个字节
        QByteArray remainingBytes = datagram.mid(63);//3263  800*4+63
        unsigned char wave[8192]={0};
        // 假设剩余的字节数是4的倍数，可以转换为unsigned int
        if (remainingBytes.size() % 4 == 0) {

            for (int i = 0; i < remainingBytes.size(); i += 4) {
                unsigned int value = *reinterpret_cast<const unsigned int*>(remainingBytes.constData() + i);

                unsigned char a= value>>20;
                if(a>=255)
                {
                    a=255;
                }
                wave[i/4] =a;
            }
        }
        int bearing=(datagram[9]+(datagram[10]*255))*4;
        unsigned char** spx_video_ptr = &spx_video;
        Wave2Cat240(1,bearing, wave, 8192, spx_video_ptr);
        QByteArray new_datagram(reinterpret_cast<const char*>(spx_video), 8227);
        spx_video_ptr=nullptr;
        qint64 bytesWritten = m_socket.writeDatagram(datagram, m_groupAddress, m_port);
        if (bytesWritten < 0) {
            qWarning("Error writing datagram: %s", m_socket.errorString().toUtf8().constData());
        }
    }

}
int FileSender::Wave2Cat240(unsigned int div_num, unsigned int bearing, unsigned char* wave, int wave_len, unsigned char** spx_video) {

    static unsigned int index = 0;
    unsigned int cat240_len = wave_len + 35;
    // 获取当前时间
    struct timespec current_time;
    clock_gettime(CLOCK_REALTIME, &current_time);
    struct tm* tm_info = localtime(&current_time.tv_sec);
    unsigned int msec = current_time.tv_nsec / 1000000;

    unsigned int t = (tm_info->tm_hour * 3600 + tm_info->tm_min * 60 + tm_info->tm_sec) * 128 + msec / 1000 * 128;

    unsigned int cell_dur = TSample * div_num * 1000000;

    index++;

    // 构建消息
    size_t msg_len = 0;
    spx_msg[msg_len++] = 0xf0;
    spx_msg[msg_len++] = (cat240_len >> 8) & 0xFF;
    spx_msg[msg_len++] = cat240_len & 0xFF;
    spx_msg[msg_len++] = 0xE7;
    spx_msg[msg_len++] = 0xA8;
    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = 0x02;

    spx_msg[msg_len++] = (index >> 24) & 0xFF;
    spx_msg[msg_len++] = (index >> 16) & 0xFF;
    spx_msg[msg_len++] = (index >> 8) & 0xFF;
    spx_msg[msg_len++] = index & 0xFF;

    spx_msg[msg_len++] = (bearing >> 8) & 0xFF;
    spx_msg[msg_len++] = bearing & 0xFF;
    spx_msg[msg_len++] = (bearing >> 8) & 0xFF;
    spx_msg[msg_len++] = bearing & 0xFF;

    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = 0x00;

    spx_msg[msg_len++] = (cell_dur >> 24) & 0xFF;
    spx_msg[msg_len++] = (cell_dur >> 16) & 0xFF;
    spx_msg[msg_len++] = (cell_dur >> 8) & 0xFF;
    spx_msg[msg_len++] = cell_dur & 0xFF;

    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = 0x04;
    spx_msg[msg_len++] = (wave_len >> 8) & 0xFF;
    spx_msg[msg_len++] = wave_len & 0xFF;
    spx_msg[msg_len++] = 0x00;
    spx_msg[msg_len++] = (wave_len >> 8) & 0xFF;
    spx_msg[msg_len++] = wave_len & 0xFF;
    spx_msg[msg_len++] = wave_len / 64; // REP

    // 复制视频数据到消息
    memcpy(spx_msg + msg_len, wave, wave_len);
    msg_len += wave_len;

    // 添加时间数据
    spx_msg[msg_len++] = (t >> 16) & 0xFF;
    spx_msg[msg_len++] = (t >> 8) & 0xFF;
    spx_msg[msg_len++] = t & 0xFF;

    *spx_video =  spx_msg;

    return msg_len;

}

/*
void FileSender::sendNextPacket() {
    if (m_file->atEnd()) {
        QByteArray endSignal = "END";
        m_socket.writeDatagram(endSignal, m_groupAddress, m_port);
        qDebug("Sending END signal");
        m_timer->stop();
        return;
    }

    QByteArray datagram(8227,'0');
    int bytesRead = m_file->read(datagram.data(), datagram.size());
    if (bytesRead < 0) {
        qWarning("Error reading from file");
        return;
    }

    qint64 bytesWritten = m_socket.writeDatagram(datagram, m_groupAddress, m_port);
    if (bytesWritten < 0) {
        qWarning("Error writing datagram: %s", m_socket.errorString().toUtf8().constData());
    }
}*/
